package cn.pzx.base_module.http

import cn.pzx.base_module.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author pzx
 * @description:
 * @date :3/3/21 3:37 PM
 */
class RetrofitClient {

//    private lateinit var retrofit: Retrofit

    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        val BASE_URL: String = "https://www.wanandroid.com"
        private lateinit var retrofit: Retrofit

    }

    private object SingletonHolder {
        val INSTANCE = RetrofitClient()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
//            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {


        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
//            .addInterceptor(LoggingInterceptor())


        if (BuildConfig.DEBUG) {
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            builder.addInterceptor(httpLoggingInterceptor.apply {
                httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            })
        }
        return builder.build()

    }


    fun getRetrofit(): Retrofit {
        return retrofit
    }

    fun create(): ApiInterface = retrofit.create(ApiInterface::class.java)


}